//
//  TelBookTabView.swift
//  telephoneBook
//
//  Created by cyptt on 2023/6/18.
//

import UIKit
import QuickLook
@available(iOS 11.0, *)
open class CHPDFColView: UIView,UICollectionViewDelegate  {
 
    

    
    var colDataSource:CHPDFDataSource? //dataSource
    
    let cellID:String = CHUtils.getClassName(CHPDFColCell.self) + "ID"   // xib CELLID 为 类名加ID
    
    var viewModel:CHPDFViewModel?  //ViewModel
//    let reHeadr:MJRefreshNormalHeader = MJRefreshNormalHeader() //下拉刷新
//    let footHeader:MJRefreshBackNormalFooter = MJRefreshBackNormalFooter() //上啦加载更多
    
    private var rowMaxCount:Int = 1
    private var selfW:CGFloat = UIScreen.main.bounds.size.width
    private var selfH:CGFloat =  UIScreen.main.bounds.size.height - 44 - UIApplication.shared.statusBarFrame.size.height
    private var isShowView = false
    private var mItemSpacing:CGFloat = 2 //item间距
    private var mLineSpacing:CGFloat = 2 //行距
    private var mItemH:CGFloat? = nil  //高度是否固定
    
    public weak var mController:UIViewController?
    public init(controller:UIViewController){
        super.init(frame: CGRect.zero)
        mController = controller
        config()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        config()
      

    
    }
    func config(){
        self.setUI()
        
        self.setPosition()
        
        self.setDataSourceViewModel()
        

//        self.viewModel?.refreshData(isMoreData: false)
        
        //  需要下拉刷新打开注释，注释 refreshData
//        self.configRefresh()
        
        //需要上拉刷新打开注释，
//        self.configPullUpRefresh()
        
    
//        self.collectView.register(UINib.init(nibName: CHUtils.getClassName(CHPDFColCell.self), bundle: nil), forCellWithReuseIdentifier: self.cellID)
        self.collectView.register(CHPDFColCell.self, forCellWithReuseIdentifier: cellID)
       
    }
    
    func setUI(){
        self.addSubview(self.collectView)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        selfW = self.frame.size.width;
        selfH = self.frame.size.height;
    }
    func setPosition(){
        self.collectView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    func setDataSourceViewModel(){
        weak var weakSelf = self
        colDataSource = CHPDFDataSource.init(identifier: self.cellID) { cell, model, indexPath, collectView in
            let cell:CHPDFColCell? = cell as? CHPDFColCell
            let model:CHPDFModel? = model as? CHPDFModel
          
            if model?.dataType == .filePathString{
                if model?.fileUrl != nil{
                    if let document = PDFDocument(url: URL.init(string: model!.fileUrl!)!) {
                        cell?.pdfView.document = document
                    }
                }
            }else if model?.dataType == .fileURL{
                if model?.url != nil{
                    if let document = PDFDocument(url: model!.url!) {
                        cell?.pdfView.document = document
                    }
                }
            }else if model?.dataType == .data{
                if model?.data != nil{
                    if let document = PDFDocument(data: model!.data!) {
                        cell?.pdfView.document = document
                    }
                }
            }
          
                    
            cell?.pageLabel.text = "\(indexPath.row + 1)/\(self.colDataSource?.datas.count ?? 0)"
       
        }
        self.viewModel = CHPDFViewModel.init(successBlock: { vModelResult, isMoreData in
            weakSelf?.colDataSource?.datas = vModelResult as! [Any]
            
            if isMoreData == false{
                weakSelf?.endHeaderRefresh()
            }else{
                weakSelf?.endFooterRefresh()
            }

        },failBlock: { vModelFailMsg in
            
        })
        
        self.collectView.dataSource  = self.colDataSource
    }

    
    /*
     初始化下拉刷新
     */
    func configRefresh(){
//        reHeadr.setRefreshingTarget(self, refreshingAction: #selector(refreshData))
//        self.collectView.mj_header = reHeadr
//        self.collectView.mj_header?.beginRefreshing()
        
    }
    
    
   /*
    下拉刷新 文件url
    */
    public func refreshData(files:[String]?){
        self.viewModel?.refreshData(isMoreData: false,files: files)
    }
    /**
     下拉刷新文件url
     */
    public func refreshData(urls:[URL]?){
        self.viewModel?.refreshData(isMoreData: false,urls: urls)
    }
    /**
     下拉刷新data
     */
    public func refreshData(datas:[Data]?){
        self.viewModel?.refreshData(isMoreData: false,datas: datas)
    }
    
    /*
     下拉停止了
     */
    func endHeaderRefresh(){
     
//        self.collectView.mj_header?.endRefreshing()
        tabReload()
    }
    
    /*
     上拉加载更多
     */
    func configPullUpRefresh(){
        
//        footHeader.setRefreshingTarget(self, refreshingAction: #selector(footReFreshData))
//     
//        self.collectView.mj_footer = footHeader
    
    }
    
    
   /*
    上拉加载更多
    */
    @objc func footReFreshData(){
        self.viewModel?.refreshData(isMoreData: true)
    }
    
    /*
     上拉结束
     */
    func endFooterRefresh(){
       
//        self.collectView.mj_footer?.endRefreshing()
        tabReload()
    }
    
    func tabReload(){
        self.collectView.reloadData()
//        self.collectView.d_reloadData()
     
    }
    
 
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var collectView = {()-> UICollectionView in
        

        
        let contentW = self.selfW
        
        print(contentW)
    
     
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        
        let allItemSpacings:CGFloat = self.mItemSpacing*CGFloat(self.rowMaxCount - 1) //间隙宽度总和
      
        //间隙高度总和
        
        let  cellcontentW:CGFloat = contentW-allItemSpacings
        print(cellcontentW)
        let  cellContentH:CGFloat =  selfH
        
        var itemH:CGFloat = cellContentH
        let itemW:CGFloat = cellcontentW/CGFloat(self.rowMaxCount)
        
        if self.mItemH != nil{
            itemH = self.mItemH!
        }
        
        layout.itemSize = CGSize.init(width: itemW, height: itemH)
        layout.minimumInteritemSpacing = self.mItemSpacing
        layout.minimumLineSpacing = self.mLineSpacing
      
      
        let rect:CGRect = CGRect.init(x: 0, y: 0, width: selfW, height: selfH);
        let collectView = UICollectionView.init(frame: rect, collectionViewLayout: layout)
       
        collectView.isPagingEnabled = true
        collectView.delegate = self
        collectView.dataSource = self.colDataSource
      
//          collectView.placeHolderDelegate = self
    
    
        collectView.backgroundColor = UIColor.clear
        if #available(iOS 11.0, *) {
    
            collectView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        
    
        return collectView
    }()
    
}


//MARK -- UICollectionViewDelegate
//@available(iOS 11.0, *)
// extension CHPDFColView{
    
     
//    func collectView(_ collectView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
//        return 60
//    }
//
//    func collectView(_ collectView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let model:TelBookModel? = self.tabdataSource?.datas[indexPath.row] as? TelBookModel
//        let sysUtils:SysToolUtils = SysToolUtils()
//        if model?.phone != nil{
//            sysUtils.callPhone(model!.phone!)
//        }else{
//            CHToast.show(msg: "电话号码异常")
//        }
//
//    }
//}
//MARK -- CHCollectionViewPlaceHolderDelegate
//@available(iOS 11.0, *)
// extension CHPDFColView{
//    
//    func makePlaceHolderView() -> UIView? {
//        
//        //MARK: - 这里添加你的占位图
//        let v:UIView = UIView()
//    
//        return v
//    }
//    func enableScrollWhenPlaceHolderViewShowing() -> Bool {
//        return true
//    }
//}

